package main

import (
	"context"
	"fmt"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/client"
	"io/ioutil"
	"log"
	"strings"
)

const (
	DOCKER_API_PORT    = ":6071"
	DOCKER_API_VERSION = "1.27"
)

func GetDockerApiUrl(host string) string {
	return "http://" + host + DOCKER_API_PORT
}

//容器与宿主机之间文件互传
func DockerCpFromContainerToHost(cli *client.Client, containerId string, src string) error {
	r, _, err := cli.CopyFromContainer(context.Background(), containerId, src)
	if err != nil {
		return err
	}

	content, err := ioutil.ReadAll(r)
	a := string(content)
	b := strings.NewReader(a)

	url2 := GetDockerApiUrl("20.26.38.125")
	cli2, err := client.NewClient(url2, DOCKER_API_VERSION, nil, nil)
	if err != nil {
		log.Print(err)
	}
	if err := cli2.CopyToContainer(context.Background(), "ca943b1374f8", "/etc/", b, types.CopyToContainerOptions{
		AllowOverwriteDirWithFile: true,
	}); err != nil {
		fmt.Println(err)
	}
	fmt.Println("11")
	return nil
}

//func GetDockerApiUrl(host string) string {
//	return "http://" + host + DOCKER_API_PORT
//}

func main() {
	url := GetDockerApiUrl("20.26.38.124")
	cli, err := client.NewClient(url, DOCKER_API_VERSION, nil, nil)
	if err != nil {
		log.Print(err)
	}
	if err := DockerCpFromContainerToHost(cli, "8789e10a1574", "/usr/local/bin/kubelet"); err != nil {
		log.Println(err)
	}
}
